package studyguide.ch09.simple;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class LowLevelMidlet extends MIDlet {

	private final Command exitCommand;
	private final Command nextCommand;
	private final Display display;
	
	private final SimpleCanvas simpleCanvas;
	private final SimpleCleanCanvas simpleCleanCanvas;
	
	private class SampleCommandListener implements CommandListener {

		public void commandAction(Command command, Displayable displayable) {
			if (command == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else if (command == nextCommand) {
				if (displayable == simpleCanvas) {
					display.setCurrent(simpleCleanCanvas);
				} else if (displayable == simpleCleanCanvas) {
					display.setCurrent(simpleCanvas);
				}
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + command);
			}
		}
		
	}
	
	public LowLevelMidlet() throws IOException {
		simpleCanvas = new SimpleCanvas();
		simpleCleanCanvas = new SimpleCleanCanvas();
		
		exitCommand = new Command("Exit", Command.EXIT, 1);
		nextCommand = new Command("Next", Command.OK, 1);
		
		simpleCanvas.addCommand(exitCommand);
		simpleCanvas.addCommand(nextCommand);
		
		simpleCleanCanvas.addCommand(exitCommand);
		simpleCleanCanvas.addCommand(nextCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		simpleCanvas.setCommandListener(listener);
		simpleCleanCanvas.setCommandListener(listener);
		display = Display.getDisplay(this);
	}
	
	protected void destroyApp(boolean unconditional) {
		// No Op
	}

	protected void pauseApp() {
		// No Op
	}

	protected void startApp() throws MIDletStateChangeException {
		display.setCurrent(simpleCanvas);
	}

}
